package com.kapcb.mvc.validator;

import cn.hutool.core.collection.CollUtil;
import com.google.common.collect.Sets;
import com.kapcb.common.enums.IntArrayValuable;
import com.kapcb.mvc.annotation.InEnum;
import org.apache.commons.collections4.CollectionUtils;

import javax.validation.ConstraintValidator;
import javax.validation.ConstraintValidatorContext;
import java.util.Arrays;
import java.util.Collection;
import java.util.Set;
import java.util.stream.Collectors;

/**
 * <a>Title: InEnumCollectionValidator </a>
 * <a>Author: Kapcb <a>
 * <a>Description: InEnumCollectionValidator <a>
 *
 * @author Kapcb
 * @version 1.0
 * @date 2024/5/1 10:30
 * @since 1.0
 */
public class InEnumCollectionValidator implements ConstraintValidator<InEnum, Collection<Integer>> {

    private Set<Integer> values;

    @Override
    public void initialize(InEnum annotation) {
        IntArrayValuable[] values = annotation.value().getEnumConstants();
        if (values.length == 0) {
            this.values = Sets.newHashSet();
        } else {
            this.values = Arrays.stream(values[0].array()).boxed().collect(Collectors.toSet());
        }
    }

    @Override
    public boolean isValid(Collection<Integer> list, ConstraintValidatorContext context) {
        // 校验通过
        if (CollectionUtils.containsAll(values, list)) {
            return true;
        }
        // 校验不通过，自定义提示语句（因为，注解上的 value 是枚举类，无法获得枚举类的实际值）
        // 禁用默认的 message 的值
        context.disableDefaultConstraintViolation();
        // 重新添加错误提示语句
        context.buildConstraintViolationWithTemplate(context.getDefaultConstraintMessageTemplate().replaceAll("\\{value}", CollUtil.join(list, ","))).addConstraintViolation();
        return false;
    }
}
